import axios from 'axios'
import { useUserStoreWidthOut } from '@/store/modules/user'
import { setting } from '@/setting/axiosSetting.js'

const userStore = useUserStoreWidthOut()

// 创建 axios 实例
const instance = axios.create({
  baseURL: setting.apiUrl,
  timeout: setting.timeout,
})

// 错误处理
const err = (error) => {
  const { $message: Message, $dialog: Modal } = window
  const { response, code, message } = error || {}
  const msg = response?.data?.message
  const err = error.toString()
  try {
    if (code === 'ECONNABORTED' && msg.indexOf('timeout') !== -1) {
      Message.error('接口请求超时,请刷新页面重试!')
      return
    }
    if (err && err.includes('Network Error')) {
      Modal.info({
        title: '网络异常',
        content: '请检查您的网络连接是否正常!',
        positiveText: '确定',
        onPositiveClick: () => {},
      })
      return
    }
  } catch (error) {
    throw new Error(error)
  }
  return Promise.reject(error)
}

// 请求拦截
instance.interceptors.request.use((config) => {
  // 判断是否管理员，如果是加上token
  if (userStore.getIsAdmin) {
    const token = userStore.getToken
    if (token) {
      // jwt token
      config.headers.Authorization = 'Bearer ' + token
    }
  }
  return config
}, err)

/**
 * 所有请求统一返回
 */
instance.interceptors.response.use((response) => {
  const { $message: Message, $dialog: Modal } = window
  if (response.request.responseType === 'blob') {
    return response
  }
  const code = response.data.code
  if (code === 401) {
    // 到登录页
    const timeoutMsg = '登录超时,请重新登录!'
    Modal.warning({
      title: '提示',
      content: '登录身份已失效，请重新登录!',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        storage.clear()
        router.replace({
          name: 'AdminLogin',
          query: {
            redirect: router.currentRoute.value.fullPath,
          },
        })
      },
      onNegativeClick: () => {},
    })
    return Promise.reject(new Error(timeoutMsg))
  } else {
    return response.data
  }
}, err)

export { instance as axios }
